#!/bin/bash
Red='\033[1;31m'
Green='\033[1;32m'
Yellow='\033[1;33m'
Blue='\033[1;34m'
Purple='\033[1;35m'
Cyan='\033[1;36m'
While='\033[1;37m'
Reset='\033[0m'
echo -e "该脚本是为新安装的CentOS7系统和Ubuntu系统进行常用的初始化，初始化的内容有：
${Blue}Ubuntu：
（01）备份原来的仓库源文件
（02）根据系统版本修改镜像仓库源为国内源
（03）关闭防火墙
（04）安装必要的包
（05）支持中文显示
（06）安装必要的包
（07）设置终端颜色
（08）配置通用alias
（09）配置通用vim设置
（10）配置时区
（11）设置历史记录
（12）设置软资源和硬资源设置
（13）设置自动更新时间
（14）内核配置优化
（15）配置DNS${Reset}
${Green}CentOS7：
（01）备份原来的仓库源文件
（02）添加镜像仓库（Base Epel）修改镜像仓库源为国内源
（03）关闭selinux
（04）关闭fiewalld
（05）关闭NetworkManager
（06）支持中文显示
（07）安装必要的包
（08）设置终端颜色
（09）配置通用alias
（10）配置通用vim设置
（11）配置时区
（12）设置历史记录
（13）设置软资源和硬资源设置
（14）设置自动更新时间
（15）内核配置优化
（16）配置DNS${Reset}
"
echo -e "${Yellow}确定要初始化请按回车，否则ctrl+c终止脚本。${Reset}"

read -p "" xxxx

#检查linux系统发行版
function CheckDistro() {
  for i in issue os-release issue.net centos-release redhat-rekease;do
    if [[ -f /etc/$i ]];then
      if grep -q "$1" /etc/$i;then
        return 0
      fi
    fi
  done
  return 1
}

#原有的仓库文件
function BackupSourceFile() {
  if CheckDistro 'CentOS';then
    mkdir -p /etc/yum.repos.d/repos_back
    if [ -d /etc/yum.repos.d/repos_back ];then
      mv /etc/yum.repos.d/*.repo /etc/yum.repos.d/repos_back
    fi
  elif CheckDistro 'Ubuntu';then
    if [ -f /etc/apt/sources.list ];then
        \cp -r /etc/apt/sources.list{,.bak}
    fi
  fi
}

#CentOS7的Base源
function AddYumBaseMirror() {
echo '
# CentOS-Base.repo
#
# The mirror system uses the connecting IP address of the client and the
# update status of each mirror to pick mirrors that are updated to and
# geographically close to the client.  You should use this for CentOS updates
# unless you are manually picking other mirrors.
#
# If the mirrorlist= does not work for you, as a fall back you can try the
# remarked out baseurl= line instead.
#
#

[base]
name=CentOS-$releasever - Base - mirrors.aliyun.com
baseurl=http://mirrors.aliyun.com/centos/$releasever/os/$basearch/
#mirrorlist=https://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=os
gpgcheck=1
gpgkey=https://mirrors.aliyun.com/centos/RPM-GPG-KEY-CentOS-7

#released updates
[updates]
name=CentOS-$releasever - Updates - repo.huaweicloud.com
baseurl=http://mirrors.aliyun.com/centos/$releasever/updates/$basearch/
#mirrorlist=https://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=updates
gpgcheck=1
gpgkey=http://mirrors.aliyun.com/centos/RPM-GPG-KEY-CentOS-7

#additional packages that may be useful
[extras]
name=CentOS-$releasever - Extras - repo.huaweicloud.com
baseurl=http://mirrors.aliyun.com/centos/$releasever/extras/$basearch/
#mirrorlist=https://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=extras
gpgcheck=1
gpgkey=http://mirrors.aliyun.com/centos/RPM-GPG-KEY-CentOS-7

#additional packages that extend functionality of existing packages
[centosplus]
name=CentOS-$releasever - Plus - repo.huaweicloud.com
baseurl=http://mirrors.aliyun.com/centos/$releasever/centosplus/$basearch/
#mirrorlist=https://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=centosplus
gpgcheck=1
enabled=0
gpgkey=http://mirrors.aliyun.com/centos/RPM-GPG-KEY-CentOS-7' > /etc/yum.repos.d/CentOS-Base.repo
}

#CentOS7Epel源
function AddYumEpelMirror() {
echo '
[epel]
name=Extra Packages for Enterprise Linux 7 - $basearch
baseurl=http://mirrors.aliyun.com/epel/7/$basearch
#metalink=https://mirrors.fedoraproject.org/#metalink?repo=epel-7&arch=$basearch&infra=$infra&content=$contentdir
failovermethod=priority
enabled=1
gpgcheck=1
gpgkey=https://mirrors.aliyun.com/epel/RPM-GPG-KEY-EPEL-7

[epel-debuginfo]
name=Extra Packages for Enterprise Linux 7 - $basearch - Debug
baseurl=http://mirrors.aliyun.com/epel/7/$basearch/debug
#metalink=https://mirrors.fedoraproject.org/#metalink?repo=epel-debug-7&arch=$basearch&infra=$infra&content=$contentdir
failovermethod=priority
enabled=0
gpgkey=https://mirrors.aliyun.com/epel/RPM-GPG-KEY-EPEL-7
gpgcheck=1

[epel-source]
name=Extra Packages for Enterprise Linux 7 - $basearch - Source
baseurl=http://mirrors.aliyun.com/epel/7/SRPMS
#metalink=https://mirrors.fedoraproject.org/#metalink?repo=epel-source-7&arch=$basearch&infra=$infra&content=$contentdir
failovermethod=priority
enabled=0
gpgkey=https://mirrors.aliyun.com/epel/RPM-GPG-KEY-EPEL-7
gpgcheck=1' > /etc/yum.repos.d/epel.repo
yum clean all
}

#Ubuntu仓库源
function AddAptBaseMirror() {
#判断Ubuntu版本
ubuntuCodename=$(lsb_release -a 2>/dev/null|awk 'END{print $NF}')
echo "
# 默认注释了源码镜像以提高 apt update 速度，如有需要可自行取消注释
deb http://mirrors.aliyun.com/ubuntu/ ${ubuntuCodename} main restricted universe multiverse
# deb-src https://mirrors.aliyun.com/ubuntu/ ${ubuntuCodename} main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ ${ubuntuCodename}-updates main restricted universe multiverse
# deb-src https://mirrors.aliyun.com/ubuntu/ ${ubuntuCodename}-updates main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ ${ubuntuCodename}-backports main restricted universe multiverse
# deb-src https://mirrors.aliyun.com/ubuntu/ ${ubuntuCodename}-backports main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ ${ubuntuCodename}-security main restricted universe multiverse
# deb-src https://mirrors.aliyun.com/ubuntu/ ${ubuntuCodename}-security main restricted universe multiverse

# 预发布软件源，不建议启用
# deb http://mirrors.aliyun.com/ubuntu/ ${ubuntuCodename}-proposed main restricted universe multiverse
# deb-src https://mirrors.aliyun.com/ubuntu/ ${ubuntuCodename}-proposed main restricted universe multiverse" > /etc/apt/sources.list
apt update
}

#Almalinux仓库源
function AddAlmalinuxMirror() {
      sed -e 's|^mirrorlist=|#mirrorlist=|g' \
          -e 's|^# baseurl=https://repo.almalinux.org|baseurl=https://mirrors.aliyun.com|g' \
          -e  's|^gpgkey=file:///etc/pki/rpm-gpg/|gpgkey=https://mirrors.aliyun.com/almalinux/|g' \
          -i \
          /etc/yum.repos.d/almalinux*.repo
}

#Ubuntu1804关闭防火墙
function CloseUfw() {
  if command -v ufw &> /dev/null;then
    ufw disable
  fi
}

#关闭SELINUX
function CloseSELINUX() {
  [[ $(grep SELINUX=enforcing /etc/sysconfig/selinux) ]]||[[ $(grep SELINUX=permissive /etc/sysconfig/selinux) ]];setenforce 0&&sed -i 's/^SELINUX=.*/SELINUX=disabled/' /etc/selinux/config
}

#关闭Firewalld
function CloseFireWalld() {
  #设置关闭火墙
  systemctl stop firewalld
  systemctl disable firewalld
}

#关闭NetworkManager
function CloseNetworkManager(){
  #关闭NetworkManager
  systemctl stop NetworkManager
  systemctl disable NetworkManager
}

#初始化linux系统
function InitSystem() {
  if CheckDistro 'CentOS';then
    echo -e "${Red}This OS is CentOS${Rest}"
    BackupSourceFile
    AddYumBaseMirror
    AddYumEpelMirror
    CloseSELINUX
    CloseFireWalld
    CloseNetworkManager
  elif CheckDistro 'Ubuntu';then
    echo -e "${Red}This OS is Ubuntu${Rest}"
    CloseUfw
    BackupSourceFile
    AddAptBaseMirror
  elif CheckDistro 'AlmaLinux';then
    echo -e "${Red}This OS is AlmaLinux${Rest}"
    BackupSourceFile
    AddAlmalinuxMirror
    CloseSELINUX
    CloseFireWalld
  elif CheckDistro 'Debian';then
    echo -e "${Red}This OS is Debian${Rest}"
  elif CheckDistro 'Fedora';then
    echo -e "${Red}This OS is Fedora${Rest}"
  elif CheckDistro 'Alibaba Cloud Linux (Aliyun Linux) 2';then
    echo -e "${Red}This OS is Alibaba Cloud Linux (Aliyun Linux) 2${Rest}"
  elif CheckDistro 'Alibaba Cloud Linux 3';then
    echo -e "${Red}This OS is Alibaba Cloud Linux 3${Rest}"
  else
    echo -e "${Red}Linux release version not supported!${Rest}"
    exit 1
  fi
}
#添加支持中文显示
function SupportSimpleChinese() {
  if CheckDistro 'CentOS';then
    echo -e "${Red}CentOS7默认支持中文显示，如不支持请自行修改${Reset}"
  elif CheckDistro 'Ubuntu';then
      apt-get -y install locales
      if ! $(grep LANG=en_US.UTF-8 ~/.bashrc);then
          echo 'export LANG=en_US.UTF-8'|tee -a /etc/profile && source /etc/profile
      fi
      sed -i 's@^ACTIVE_CONSOLES.*@ACTIVE_CONSOLES="/dev/tty[1-2]"@' /etc/default/console-setup
      locale-gen en_US.UTF-8
  elif CheckDistro 'AlmaLinux';then
    echo -e "${Red}AlmaLinux默认支持中文显示，如不支持请自行修改${Reset}"
cat > /etc/default/locale << EOF
LANG=en_US.UTF-8
LANGUAGE=en_US:en
EOF
  fi
}

#安装基础软件
function InstallBaseSoft() {
  if CheckDistro 'CentOS';then
    yum clean all
    PkgList="curl wget unzip gcc vim swig swig automake make perl cpio git lrzsz iftop nethogs ntpdate nload htop ifstat iotop sysstat lsb-release"
    for Package in ${PkgList}
    do
      yum install -y $Package
    done
  elif CheckDistro 'Ubuntu';then
    PkgList="curl wget unzip gcc swig automake make perl cpio git iftop nethogs nload htop ifstat iotop iostat vim lsb-core iproute2 telnet traceroute nfs-kernel-server nfs-common lrzsz tree openssl libssl-dev libpcre3 libpcre3-dev zlib1g-dev ntpdate tcpdump openssh-server zip"
    for Package in ${PkgList};
    do
      apt-get -y install $Package
    done
  elif CheckDistro 'AlmaLinux';then
    dnf clean all
    PkgList="curl wget unzip gcc vim swig swig automake make perl cpio git lrzsz iftop nethogs ntpdate nload htop ifstat iotop sysstat lsb-release"
    for Package in ${PkgList}
        do
          dnf install -y $Package
        done
  fi
}

#设置终端颜色
function SetPS1() {
  if CheckDistro 'CentOS';then
    [ -z "$(grep ^PS1 ~/.bashrc)" ] && echo "PS1='\[\e[1;32m\][\[\e[1;32m\]\u\[\e[1;32m\]@\h\[\e[1;34m\] \w\[\e[1;32m\]]\[\e[0m\]\\$ '" >> ~/.bashrc
  elif CheckDistro 'Ubuntu';then
    [ -z "$(grep ^PS1 ~/.bashrc)" ] && echo "PS1='\${debian_chroot:+(\$debain_chroot)}\\[\\e[1;32m\\]\\u@\\h\\[\\033[00m\\]:\\[\\033[01;34m\\]\\w\\[\\033[00m\\]\\$ '" >> ~/.bashrc
  elif CheckDistro 'AlmaLinux';then
    [ -z "$(grep ^PS1 ~/.bashrc)" ] && echo "PS1='\[\e[1;32m\][\[\e[1;32m\]\u\[\e[1;32m\]@\h\[\e[1;34m\] \w\[\e[1;32m\]]\[\e[0m\]\\$ '" >> ~/.bashrc
  fi
}

#添加通用alias
function SetCommonAlias() {
cat > /etc/profile.d/alias.sh << EOF
HISTSIZE=10000
HISTTIMEFORMAT="%F %T \$(whoami) "

alias l='ls -AFhlt --color=auto'
alias lh='l | head'
alias ll='ls -l --color=auto'
alias ls='ls --color=auto'
alias vi=vim

GREP_OPTIONS="--color=auto"
alias grep='grep --color'
alias egrep='egrep --color'
alias fgrep='fgrep --color'
EOF
source /etc/profile.d/alias.sh
}

#配置通用vim设置
function SetCommonVim() {
  if [[ -f /etc/vim/vimrc ]];then
    sed -i 's@^"syntax on@syntax on@' /etc/vim/vimrc
    echo 'set nu' >> /etc/vim/vimrc
    echo 'set ruler' >> /etc/vim/vimrc
    echo 'set cursorline' >> /etc/vim/vimrc
    echo 'set paste' >> /etc/vim/vimrc
  else
    echo 'There is no vimrc'
  fi
}

#设置时区
function SetTimeZone() {
  rm -rf /etc/localtime
  ln -svf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
}

#设置历史记录
function SetHistory() {
  [ -z "$(grep history-timestamp ~/.bashrc)" ] && echo "PROMPT_COMMAND='{ msg=\$(history 1 | { read x y; echo \$y; });user=\$(whoami); echo \$(date \"+%Y-%m-%d %H:%M:%S\"):\$user:\`pwd\`/:\$msg ---- \$(who am i); } >> /tmp/\`hostname\`.\`whoami\`.history-timestamp'" >> ~/.bashrc
}

#设置硬软资源限制
function SetLimit() {
  if CheckDistro 'CentOS';then
    [ -e /etc/security/limits.d/*nproc.conf ] && rename nproc.conf nproc.conf_bk /etc/security/limits.d/*nproc.conf
  elif CheckDistro 'Ubuntu';then
    [ -e /etc/security/limits.d/*nproc.conf ] && rename nproc.conf nproc.conf_bk /etc/security/limits.d/*nproc.conf
  elif CheckDistro 'Ubuntu';then
    [ -z "$(grep 'session required pam_limits.so' /etc/pam.d/common-session)" ] && echo "session required pam_limits.so" >> /etc/pam.d/common-session
  fi
  sed -i '/^# End of file/,$d' /etc/security/limits.conf
cat >> /etc/security/limits.conf <<EOF
# End of file
#root账户的资源软限制和硬限制
root soft core unlimited
root hard core unlimited
root soft nproc 1000000
root hard nproc 1000000
root soft nofile 1000000
root hard nofile 1000000
root soft memlock 32000
root hard memlock 32000
root soft msgqueue 8192000
root hard msgqueue 8192000
#其他账户的资源软限制和硬限制
* soft core unlimited
* hard core unlimited
* soft nproc 1000000
* hard nproc 1000000
* soft nofile 1000000
* hard nofile 1000000
* soft memlock 32000
* hard memlock 32000
* soft msgqueue 8192000
* hard msgqueue 8192000
EOF
ulimit -SHn 1000000
}

#设置自动更新时间
function SetUpdateTime() {
  if CheckDistro 'CentOS';then
    which ntpdate || yum clean all;yum install -y ntpdate
    ntpdate pool.ntp.org
    #如果该文件不存在或该文件存在但是内容为空，就添加ntpdate的定时任务
    [ ! -e "/var/spool/cron/root" -o -z "$(grep ntpdate /var/spool/cron/root 2> /dev/null)" ] && { echo "*/20 * * * * $(which ntpdate) pool.ntp.org > /dev/null 2>&1" >> /var/spool/cron/root;chmod 600 /var/spool/cron/root;}
  elif CheckDistro 'Ubuntu';then
    which ntpdate || apt-get update;apt install -y ntpdate
    ntpdate pool.ntp.org
    #如果该文件不存在或该文件存在但是内容为空，就添加ntpdate的定时任务
    [ ! -e "/var/spool/cron/crontabs/root" -o -z "$(grep ntpdate /var/spool/cron/crontabs/root 2> /dev/null)" ] && { echo "*/20 * * * * $(which ntpdate) pool.ntp.org > /dev/null 2>&1" >> /var/spool/cron/crontabs/root;chmod 600 /var/spool/cron/crontabs/root;}
  fi
}

#设置内核参数
function SetSysctl() {
[ -z "$(grep 'fs.file-max' /etc/sysctl.conf)" ] && cat >> /etc/sysctl.conf << EOF
#这个参数定义了系统中最大的文件句柄数。文件句柄是用于访问文件的数据结构。增加这个值可以提高系统同时打开文件的能力。
fs.file-max = 1000000
#inotify是Linux内核中的一个机制，用于监视文件系统事件。这个参数定义了每个用户可以创建的inotify实例的最大数量。
fs.inotify.max_user_instances = 8192
#这个参数定义了TCP连接中，等待关闭的时间。当一端发送FIN信号后，等待对端关闭连接的超时时间。
net.ipv4.tcp_fin_timeout = 30
#这个参数定义了内核路由表清理的时间间隔，单位是秒。它影响路由缓存的生命周期。
net.ipv4.route.gc_timeout = 100
#这个参数定义了每个网络设备接收队列在每个时间间隔中可以处理的数据包数量。
net.core.netdev_budget = 5000
# Controls source route verification
net.ipv4.conf.default.rp_filter = 1
net.ipv4.ip_nonlocal_bind = 1
net.ipv4.ip_forward = 1
# Do not accept source routing
net.ipv4.conf.default.accept_source_route = 0
# Controls the System Request debugging functionality of the kernel
kernel.sysrq = 0
# Controls whether core dumps will append the PID to the core filename.
# Useful for debugging multi-threaded applications.
kernel.core_uses_pid = 1
# Controls the use of TCP syncookies
#当系统遭受SYN洪水攻击时，启用syncookies可以防止系统资源被耗尽。SYN cookies是一种机制，用于在TCP三次握手中保护服务器端资源。
net.ipv4.tcp_syncookies = 1
# Disable netfilter on bridges.
#net.bridge.bridge-nf-call-ip6tables = 0
#net.bridge.bridge-nf-call-iptables = 0
#net.bridge.bridge-nf-call-arptables = 0
# Controls the default maxmimum size of a mesage queue
kernel.msgmnb = 65536
# # Controls the maximum size of a message, in bytes
kernel.msgmax = 65536
# Controls the maximum shared segment size, in bytes
kernel.shmmax = 68719476736
# Controls the maximum number of shared memory segments, in pages
kernel.shmall = 4294967296
# TCP kernel paramater
net.ipv4.tcp_mem = 786432 1048576 1572864
net.ipv4.tcp_rmem = 4096 87380 4194304
net.ipv4.tcp_wmem = 4096 16384 4194304
net.ipv4.tcp_window_scaling = 1
net.ipv4.tcp_sack = 1
# socket buffer
net.core.wmem_default = 8388608
net.core.rmem_default = 8388608
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
#这个参数定义了网络设备接收队列的最大长度。当接收队列已满时，新的数据包将被丢弃。
net.core.netdev_max_backlog = 262144
#这个参数定义了监听队列的最大长度。当服务器正在处理的连接数超过此值时，新的连接请求将被拒绝。
net.core.somaxconn = 32768
net.core.optmem_max = 81920
# TCP conn
#这个参数定义了TCP连接请求的队列长度。当系统处理不及时时，超过该队列长度的连接请求将被拒绝。
net.ipv4.tcp_max_syn_backlog = 262144
#这个参数定义了在发送SYN请求后，等待对端回应的次数。超过指定次数后仍未响应，连接将被认为失败。
net.ipv4.tcp_syn_retries = 3
net.ipv4.tcp_retries1 = 3
net.ipv4.tcp_retries2 = 15
# tcp conn reuse
#禁用TCP时间戳。时间戳可以用于解决网络中的数据包乱序问题，但在高负载环境下可能会增加开销。
net.ipv4.tcp_timestamps = 0
#启用该参数后，可以允许将TIME-WAIT状态的TCP连接重新用于新的连接。这可以减少系统中TIME-WAIT连接的数量。
#net.ipv4.tcp_tw_reuse = 0
net.ipv4.tcp_tw_reuse = 1
#net.ipv4.tcp_tw_recycle = 0
net.ipv4.tcp_fin_timeout = 1
#这个参数定义了系统同时保持TIME-WAIT状态的最大数量。超过这个数量的连接将被立即关闭。
net.ipv4.tcp_max_tw_buckets = 20000
#这个参数定义了系统中允许存在的最大孤立（没有关联的父连接）TCP连接数量。超过这个数量的孤立连接将被立即关闭。
net.ipv4.tcp_max_orphans = 3276800
#这个参数定义了在发送SYN+ACK回应后，等待对端发送ACK的次数。超过指定次数后仍未收到ACK，连接将被认为失败。
net.ipv4.tcp_synack_retries = 1
# keepalive conn
net.ipv4.tcp_keepalive_time = 300
net.ipv4.tcp_keepalive_intvl = 30
net.ipv4.tcp_keepalive_probes = 3
#这个参数定义了本地端口的范围，用于分配给发送请求的应用程序。它限制了可用于客户端连接的本地端口范围。
net.ipv4.ip_local_port_range = 1024 65000
# swap
vm.overcommit_memory = 0
vm.swappiness = 10
#net.ipv4.conf.eth1.rp_filter = 0
#net.ipv4.conf.lo.arp_ignore = 1
#net.ipv4.conf.lo.arp_announce = 2
#net.ipv4.conf.all.arp_ignore = 1
#net.ipv4.conf.all.arp_announce = 2
EOF
sysctl -p
}

#设置DNS
function SetDns() {
  [ -z "$(grep nameserver /etc/resolv.conf 2> /dev/null)" ] && echo -e "nameserver 114.114.114.114\nnameserver 223.5.5.5\nnameserver 223.6.6.6" >> /etc/resolv.conf
}

InitSystem
SupportSimpleChinese
InstallBaseSoft
SetPS1
SetCommonAlias
SetCommonVim
SetTimeZone
SetHistory
SetLimit
SetUpdateTime
SetSysctl
SetDns
echo -e "${Green}脚本执行完成，请退出本终端并重新登录.${Reset}"